import 'dart:async';

import '../../../../commons.dart';
import 'package:tencent_kit/tencent_kit.dart';

class QQMan extends GetxController {
  Completer<TencentLoginResp?>? loginCompleter;

  Future<bool> isInstalled() {
    return TencentKitPlatform.instance.isQQInstalled();
  }

  Future<TencentLoginResp?>? login() async {
    loginCompleter = Completer<TencentLoginResp?>();

    await TencentKitPlatform.instance.login(
      scope: <String>[TencentScope.kGetSimpleUserInfo],
    );
    return loginCompleter?.future;
  }

  Future<void> share(
      {required String title,
      required String desc,
      required String webpageUrl}) {
    return TencentKitPlatform.instance.shareWebpage(
      scene: TencentScene.kScene_QQ,
      title: title,
      summary: desc,
      targetUrl: webpageUrl,
    );
  }

  void _listener(resp) {
    if (resp is TencentLoginResp) {
      final String content = 'login: ${resp.openid} - ${resp.accessToken}';
      Get.log('登录$content');
      if (loginCompleter != null && !loginCompleter!.isCompleted) {
        loginCompleter?.complete(resp);
      }
    } else if (resp is TencentShareMsgResp) {
      final String content = 'share: ${resp.ret} - ${resp.msg}';
      Get.log('分享$content');
    }
  }

  @override
  void onInit() {
    TencentKitPlatform.instance.respStream().listen(_listener);

    _register();
    super.onInit();
  }

  void _register() async {
    await TencentKitPlatform.instance.setIsPermissionGranted(granted: true);
    TencentKitPlatform.instance.registerApp(
      appId: AppConfig.qqAppId,
      universalLink: AppConfig.universalLink,
    );
  }
}

extension QQEx on GetInterface {
  QQMan get qq => find<QQMan>();
}
